﻿using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicLoggerModule.Model
{
    public class SqlserverLogger : ILogger
    {
        public IDisposable? BeginScope<TState>(TState state) where TState : notnull
        {
            return null;
        }

        //判断日志级别
        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        /// <summary>
        /// 将日志信息写入数据库
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel"></param>
        /// <param name="eventId"></param>
        /// <param name="state"></param>
        /// <param name="exception"></param>
        /// <param name="formatter"></param>
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            if (!IsEnabled(logLevel)) 
            {
                return;
            }
            //格式化日志信息
            var message = formatter(state, exception);
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                //Server=localhost;Port=3306;Database=YDT-Ebusiness;Uid=root;Pwd=123456; mysql
                //Data Source=zdf;Initial Catalog=Ydt_Test;Integrated Security=True;Trust Server Certificate=True  sqlserver
                ConnectionString = "Server=localhost;Port=3306;Database=YDT-Ebusiness;Uid=root;Pwd=123456;",
                DbType = DbType.MySql,
                IsAutoCloseConnection = true
            },
            db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    //获取原生SQL推荐 5.1.4.63  性能OK
                    //Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                    //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                    //Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer,sql,pars))
           
                };
            });

            Db.CodeFirst.InitTables(typeof(LoggerModel));//这样一个表就能成功创建了

            LoggerModel loggerModel = new LoggerModel() { Message = message, LoggetLever = logLevel.ToString(),DateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")};
            int i = Db.Insertable<LoggerModel>(loggerModel).ExecuteCommand();
        }
    }
}
